package com.multi.thread.chapter04.demo12;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 *	使用condition实现顺序执行
 */
public class TestCondition {
	
	volatile private static int nextPrintWho = 1;
	
	private static ReentrantLock lock = new ReentrantLock();
	final private static Condition conditionA = lock.newCondition();
	final private static Condition conditionB = lock.newCondition();
	final private static Condition conditionC = lock.newCondition();
	
	public static void main(String[] args) {
		Thread a = new Thread() {
			@Override
			public void run() {
				try {
					lock.lock();
					while (nextPrintWho != 1) {
						conditionA.await();
					}
					for (int i = 0; i < 3;i ++) {
						System.out.println("ThreadA " + (i + 1));
					}
					System.out.println();
					nextPrintWho = 2;
					conditionB.signalAll();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		};
		
		Thread b = new Thread() {
			@Override
			public void run() {
				try {
					lock.lock();
					while (nextPrintWho != 2) {
						conditionB.await();
					}
					for (int i = 0; i < 3;i ++) {
						System.out.println("ThreadB " + (i + 1));
					}
					System.out.println();
					nextPrintWho = 3;
					conditionC.signalAll();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		};
		
		Thread c = new Thread() {
			@Override
			public void run() {
				try {
					lock.lock();
					while (nextPrintWho != 3) {
						conditionC.await();
					}
					for (int i = 0; i < 3;i ++) {
						System.out.println("ThreadC " + (i + 1));
					}
					System.out.println();
					nextPrintWho = 1;
					conditionA.signalAll();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		};
		
		Thread ta = new Thread(a);
		ta.start();
		Thread tb = new Thread(b);
		tb.start();
		Thread tc = new Thread(c);
		tc.start();
	}

}
